package servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sessions.UserManagerRemote;
import exceptions.AdminAuthenticationException;
import exceptions.AuthenticationException;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		try {
			Hashtable<String, String> env = new Hashtable<String, String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL, "localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = jndiContext.lookup("UserManager/remote");
			UserManagerRemote r = (UserManagerRemote) ref;
			try {
				r.adminAuthenticate(username, password);
				session.setAttribute("admin", "yes");
				session.setAttribute("username", username);
				response.sendRedirect("home.jsp");
				return;
			} catch (AdminAuthenticationException aae) {
				try {
					r.authenticate(username, password);
					session.setAttribute("username", username);
					response.sendRedirect("home.jsp");
					return;
				} catch (AuthenticationException ae) {
					String error = "<font face='tahoma' size='2'>Username e/o password errati.</font><br><font face='tahoma' size='2'>Torna alla <a href='home.jsp' style='color: blue; text-decoration: underline'>Home Page</a></font>";
					session.setAttribute("error", error);
					response.sendRedirect("error.jsp");
					return;
				}
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
	}
	
}
